# -*- coding: utf-8 -*-
from pymysql import connect


def singleton(cls):
    instances = {}

    def _singleton(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return _singleton


@singleton
class CSdb(object):
    def __init__(self, server_address='tencentcdb'):
        self.server_address = server_address
        # self.conn = connect(host='122.51.36.186', port=3306, user='root', password='Bomi81001', database='cs',
        #                     charset='utf8')

        # self.conn = connect(host='150.109.32.129', port=3306, user='hkbomi', password='hkbomi81001', database='cs',
        #                     charset='utf8')
        self.conn = self.get_conn()
        # self.conn = connect(host='150.109.32.129', port=3306, user='hkbomi', password='hkbomi81001', database='cs',
        #                     charset='utf8')
        self.cursor = self.conn.cursor()

    def get_conn(self):
        if self.server_address == 'tencentcdb':
            # conn = connect(host='gz-cdb-cpoe2wz3.sql.tencentcdb.com', port=60017, user='bomi', password='bomi81001',
            #                 database='cs',
            #                 charset='utf8')
            conn = connect(host='gz-cdb-aq76i6tl.sql.tencentcdb.com', port=63698, user='bomi_serve',
                           password='Bomi_81001Serve',
                           database='cs',
                           charset='utf8')
        elif self.server_address == 'localhost':
            conn = connect(host='localhost', port=3306, user='root', password='123', database='cs', charset='utf8')
        else:
            raise Exception('请从tencentcdb，和localhost中选择')
        return conn

    # def re_acquire_conn(self):
    #     self.conn = connect(host='gz-cdb-cpoe2wz3.sql.tencentcdb.com', port=60017, user='bomi', password='bomi81001',
    #                         database='cs',
    #                         charset='utf8')
    #     self.cursor = self.conn.cursor()
    #
    #     return self.conn, self.cursor

    def Query(self, sql):
        """
        查询数据
        :param sql:
        :return:
        """
        # try:
        self.cursor.execute(sql)
        # except Exception as e:
        #
        #     self.conn, self.cursor = self.re_acquire_conn()
        #     self.cursor.execute(sql)
        return self.cursor.fetchall()

    def Operating(self, sql):
        # try:
        self.cursor.execute(sql)
        self.conn.commit()
        # except Exception as e:
        #
        #     self.conn, self.cursor = self.re_acquire_conn()
        #     self.cursor.execute(sql)
        #     self.conn.commit()
        return True

    def execute_sql(self, sql):
        item_list = list()
        self.cursor.execute(sql)  # 执行sql语句
        for item in self.cursor.fetchall():  # 获取结果
            # print(type(item[1]))
            item_list.append(item)
        return item_list
